package com.dis.service.controller.admin;

import com.dis.common.annotation.CheckPermission;
import com.dis.pojo.entity.Region;
import com.dis.pojo.vo.RegionTreeVO;
import com.dis.pojo.dto.RegionDTO;
import com.dis.common.result.Result;
import com.dis.service.service.RegionService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/admin/region")
@Api(tags = "行政区域管理接口")
@Slf4j
public class RegionController {

    @Autowired
    private RegionService regionService;

    /**
     * 获取区域树形结构
     * @return
     */
    @GetMapping("/tree")
    @ApiOperation("获取区域树形结构")
    @CheckPermission("region:query")
    public Result<List<RegionTreeVO>> getTree() {
        log.info("获取区域树形结构");
        List<RegionTreeVO> tree = regionService.getRegionTree();
        return Result.success(tree);
    }

    /**
     * 根据ID查询区域详情
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    @ApiOperation("根据ID查询区域详情")
    @CheckPermission("region:query")
    public Result<Region> getById(@PathVariable Integer id) {
        log.info("根据ID查询区域详情: {}", id);
        Region region = regionService.getById(id);
        return Result.success(region);
    }

    @PostMapping
    @ApiOperation("新增区域")
    @CheckPermission("region:add")
    public Result save(@RequestBody RegionDTO regionDTO) {
        log.info("新增区域: {}", regionDTO);
        regionService.save(regionDTO);
        return Result.success();
    }

    @PutMapping
    @ApiOperation("更新区域")
    @CheckPermission("region:edit")
    public Result update(@RequestBody RegionDTO regionDTO) {
        log.info("更新区域: {}", regionDTO);
        regionService.update(regionDTO);
        return Result.success();
    }

    @DeleteMapping("/{id}")
    @ApiOperation("删除区域")
    @CheckPermission("region:delete")
    public Result delete(@PathVariable Integer id) {
        log.info("删除区域: {}", id);
        regionService.deleteById(id);
        return Result.success();
    }

    /**
     * 修改区域状态
     * @param status 需要改成的状态
     * @param id     区域ID，即regionId
     * @return
     */
    @PostMapping("/status/{status}")
    @ApiOperation("修改区域状态")
    @CheckPermission("region:status")
    public Result changeStatus(@PathVariable Integer status, @RequestParam Integer id) {
        log.info("修改区域状态: id={}, status={}", id, status);
        regionService.changeStatus(id, status);
        return Result.success();
    }
    
    @GetMapping("/children/{parentId}")
    @ApiOperation("根据父ID获取子地区列表")
    @CheckPermission("region:query")
    public Result<List<Region>> getRegionsByParentId(@PathVariable Integer parentId) {
        log.info("根据父ID获取子地区列表：parentId={}", parentId);
        List<Region> regions = regionService.getRegionsByParentId(parentId);
        return Result.success(regions);
    }
}